function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import React, { useState, useEffect } from 'react';
import { Button, Drawer, Form } from 'antd';
import SearchBase from '../SearchBase';
import { nextTick } from '../../tools';
import { getDefaultItems } from './tools';

const CreateNode = function CreateNode({
  visible,
  onClose,
  onSubmit,
  onLoad,
  node,
  laneOptions = []
}) {
  var _node$data2;

  const _Form$useForm = Form.useForm(),
        _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
        form = _Form$useForm2[0];

  const _useState = useState([]),
        _useState2 = _slicedToArray(_useState, 2),
        items = _useState2[0],
        setItems = _useState2[1];

  const _useState3 = useState(false),
        _useState4 = _slicedToArray(_useState3, 2),
        loading = _useState4[0],
        setLoading = _useState4[1];

  useEffect(() => {
    onLoad && onLoad(form);
  }, []);

  function getSupportLaneOptions(laneOptions, target) {
    if (!Array.isArray(target) || !target.length) {
      return laneOptions;
    }

    const lanesMap = laneOptions.reduce((p, c) => {
      p[c.value] = c;
      return p;
    }, {});
    return target.map(l => lanesMap[l]);
  }

  useEffect(() => {
    if (!visible) return;

    if (!node) {
      setItems([]);
    } else {
      var _node$data;

      const data = node.data;
      const moduleProps = window._moduleProps || {};
      const modules = window._modules || {};
      const moduleType = data.moduleType,
            target = data.target;
      const modulePropItems = [...getDefaultItems(getSupportLaneOptions(laneOptions, target), Object.values(modules), !!(node !== null && node !== void 0 && (_node$data = node.data) !== null && _node$data !== void 0 && _node$data.id)), ...(moduleProps[moduleType] || [])];
      const initValue = modulePropItems.reduce((p, c) => {
        p[c.name] = data[c.name];
        return p;
      }, {});
      setItems(modulePropItems);
      nextTick(() => form.setFieldsValue(initValue));
    }
  }, [visible, node, laneOptions]);

  const submitForm = () => {
    form.validateFields().then( /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(values) {
        var copyNode, ret;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              setLoading(true);

              if (!onSubmit) {
                _context.next = 11;
                break;
              }

              copyNode = node.clone();
              copyNode.setData(values);
              _context.next = 6;
              return onSubmit(copyNode);

            case 6:
              ret = _context.sent;
              setLoading(false);
              if (ret) onClose();
              _context.next = 13;
              break;

            case 11:
              setLoading(false);
              onClose();

            case 13:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }());
  };

  return /*#__PURE__*/React.createElement(Drawer, {
    title: `${node !== null && node !== void 0 && (_node$data2 = node.data) !== null && _node$data2 !== void 0 && _node$data2.id ? '编辑' : '新建'}节点`,
    placement: "right",
    className: "ra-arch-createNode",
    closable: false,
    onClose: onClose,
    visible: visible,
    getContainer: () => document.body,
    extra: /*#__PURE__*/React.createElement(Button, {
      loading: loading,
      type: "primary",
      ghost: true,
      size: "small",
      onClick: submitForm
    }, "\u63D0\u4EA4")
  }, /*#__PURE__*/React.createElement(SearchBase, {
    form: form,
    items: items
  }));
};

export default CreateNode;